<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>防抖</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: rgb(143, 118, 118);
            text-align: center;
            line-height: 100px;
            color: aliceblue;
        }
    </style>
</head>

<body>
    <div></div>

    <script>
        const div = document.querySelector('div')

        // 防抖:一段时间内触发某个事件,最后一次才执行
        let num = 1
        function mouseMove() {
            div.innerHTML = num++
            console.log(num,'防抖');

        }

        // 封装一个防抖函数
        function debounce(fn, t) {
            let timer = null
            // 返回一个匿名函数
            return function () {
                // 判断有没有定时器,有就清除
                if (timer) clearTimeout(timer)
                // 没有就开启
                timer = setTimeout(() => {
                    fn() // 调用函数
                }, t)

            }

        }

        div.addEventListener('mousemove', debounce(mouseMove, 500))
    </script>
</body>

</html>